import styles from './Table.module.scss'
import Detail from './Detail'
import Dialog from '@renderer/components/dialog'

import { dateFormat } from '@renderer/utils/utils'
import { getGroupChatNoticeList, delGroupChatNotice, startGroupChatNotice, pauseGroupChatNotice } from '@renderer/ajax/api/publishGroupNotice'
import { ElTable, ElTableColumn, ElPagination, ElButton, ElProgress, ElPopover, ElTag, ElEmpty } from 'element-plus'
import { reactive, ref, defineComponent, watch, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'publishGroupNoticeTable',
  props: {
    fetchParams: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props, { emit, slots }) {
    const router = useRouter()
    const state = reactive({
      list: [],
      total: 0,
      id: '', // 当前操作的id
      type: 0, //0:暂停 1:开始
      message: '',
      page: 1,
      page_size: 15
    })
    const DialogData = reactive({
      visible: false,
      width: '500px',
      title: '',
      content: '',
      footer: ['取消', '确定', 'center']
    })
    const onMessage = () => ElMessage.success(state.message)
    // 弹框确定
    const onSubmit = async () => {
      // 0 暂停 1 开始  2 删除
      state.type == 0 && (await pauseGroupChatNotice({Id: state.id}))
      state.type == 1 && (await startGroupChatNotice({Id: state.id}))
      state.type == 2 && (await delGroupChatNotice({Id: state.id}))
      state.type == 2 && (state.page = (state.total - 1) % state.page_size === 0 ? state.page-- : state.page)
      getData()
      onMessage()
      DialogData.visible = false
    }
    const DetailRef = ref<any>(null)
    const getData = async () => {
      let params = {
        ...props.fetchParams,
        Page: state.page || 1,
        PageSize: state.page_size || 15
      }
      const res = await getGroupChatNoticeList(JSON.parse(JSON.stringify(params)))
      console.log(res)
      state.list = res?.Data || []
      state.total = res?.Total || 0
    }
    // 定时器5秒自动刷新页面，离开页面销毁
    let timer: any = null
    onMounted(() => {
      console.log('开启定时器')
      timer = setInterval(() => {
        getData()
      }, 5000)
    })
    onUnmounted(() => {
      console.log('销毁定时器')
      clearInterval(timer)
    })
    watch(
      () => props.fetchParams,
      () => {
        getData()
      },
      { deep: true, immediate: true }
    )

    const onBegin = async (row: any) => {
      DialogData.title = '开始任务'
      state.message = '开始成功'
      DialogData.content = '确定开始所选任务吗？'
      DialogData.visible = true
      state.id = row.Id
      state.type = 1
    }
    const onPaused = async (row: any) => {
      DialogData.title = '暂停任务'
      state.message = '暂停成功'
      DialogData.content = '确定暂停所选任务吗？'
      DialogData.visible = true
      state.id = row.Id
      state.type = 0
    }
    const onDel = async (row: any) => {
      console.log('删除参数', { Id: row.Id })
      DialogData.title = '删除任务'
      state.message = '删除成功'
      DialogData.content = '确定删除所选任务吗？（进行中、已暂停的任务删除后将终止任务）'
      DialogData.visible = true
      state.id = row.Id
      state.type = 2
    }
    const onLook = (row: any) => {
      DetailRef.value.onState(row)
    }
    const onSizeChange = (v: number) => {
      state.page_size = v
      getData()
    }
    const onCurrentChange = (v: number) => {
      state.page = v
      getData()
    }
    // 渲染标签
    const renderNotice = (row: any) => {
      return <ElPopover
        placement="bottom"
        trigger="hover"
        width={400}
        disabled={row.Notice.length < 10}
        vSlots={{
          reference: () => (
            <div class={styles.notice}>{row.Notice}</div>
          ),
          default: () => (
            <div class={styles.noticePopver} >{row.Notice}</div>
          )
        }}
      />
    }

    // 渲染空状态
    const renderEmpty = () => <ElEmpty description="当前没有正在执行的任务" />
    // 渲染当前状态
    const renderStatus = (row) => {
      const text = ['', '未开始', '进行中', '已暂停', '已完成']
      const color = ['', '#686e71', '#4d9ef8', '#eb5851', '#5fcb71']
      const jindu = row.Completed ? ((row.Completed / row.Total) * 100).toFixed(2) : 0
      return (
        <div class={styles.status}>
          <div class={styles.status_name}> {text[row.Status]}</div>
          <ElProgress class={styles.progress} text-inside={true} stroke-width={15} percentage={jindu} color={color[row.Status]} />
          <div>
            {row.Completed}/{row.Total}
          </div>
        </div>
      )
    }
    // 渲染操作按钮
    const renderBtn = (row) => {
      const BEGIN = (
        <ElButton size="small" onClick={() => onBegin(row)}>
          开始任务
        </ElButton>
      )
      const PAUSED = (
        <ElButton size="small" onClick={() => onPaused(row)}>
          暂停任务
        </ElButton>
      )
      const arr = ['', BEGIN, PAUSED, BEGIN]
      return (
        <>
          {arr[row.Status]}
          {row.Status == 1 ?
            <ElButton size="small" onClick={() => router.push({ path: '/publishGroupNotice/edit', query: { id: row.Id } })}>
              编辑
            </ElButton>
            : ''
          }
          <ElButton size="small" onClick={() => onLook(row)}>
            查看详情
          </ElButton>
          <ElButton size="small" onClick={() => onDel(row)}>
            删除
          </ElButton>
        </>
      )
    }


    return () => (
      <>
        <ElTable data={state.list} height="calc(100vh - 380px)"  vSlots={{ empty: () => renderEmpty() }}>
          <ElTableColumn label="任务标题" prop="Title" width="260" />
          <ElTableColumn label="群发公告内容" prop="Notice" width="260" vSlots={{ default: ({ row }) => renderNotice(row) }} />
          <ElTableColumn label="创建时间" prop="CreatedAt" width="220" vSlots={{ default: ({ row }) => row.CreatedAt || '--' }} />
          <ElTableColumn label="发送类型" prop="SpecifySendTime" width="260" vSlots={{ default: ({ row }) => (row.SpecifySendTime ? '定时发送' : '立即发送') }} />
          <ElTableColumn label="发送时间" width="260" vSlots={{ default: ({ row }) => (row.SendedAt || '--') }} />
          <ElTableColumn label="任务状态" prop="name" min-width="300" vSlots={{ default: ({ row }) => renderStatus(row) }} />
          <ElTableColumn label="操作" fixed="right" width="300" vSlots={{ default: ({ row }) => renderBtn(row) }} />
        </ElTable>
        <ElPagination
          class={styles.pagination}
          vModel:currentPage={state.page}
          vModel:pageSize={state.page_size}
          page-sizes={[15, 30, 50, 100]}
          background
          layout="total,  prev, pager, next,sizes, jumper"
          total={state.total}
          onSizeChange={onSizeChange}
          onCurrentChange={onCurrentChange}
        />
        <Detail ref={DetailRef} />
        <Dialog state={DialogData} onCancel={() => (DialogData.visible = false)} onConfirm={onSubmit} />
      </>
    )
  }
})
